package com.ojoin.trade.t0loan_core.web.monitor;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ojoin.trade.common.Constants;
import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.utils.json.JSONUtils;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 15-10-8
 * Time: 下午3:44
 * To change this template use File | Settings | File Templates.
 */
public class MonitorServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException{
       String methodname=req.getParameter("method");
        if("1".equals(methodname)){
            getAllinfo(req,resp);
        } else{
          getSingle(req,resp);
        }
    }

    private  void getAllinfo(HttpServletRequest req, HttpServletResponse resp)throws ServletException{
       ThreadEntry[] ts=ThreadTrace.getInstance().getAllThreadInfo();
      //  ThreadEntry[] ts=getinfos();
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("status","ok");
        map.put("result",ts);
        String mapstr=JSONUtils.toJSONString(map);
        try{
            resp.getOutputStream().write(mapstr.getBytes(Constants.ENCODING));
            resp.setContentType("text/json; charset=UTF-8");
        }catch(Exception e){
            throw new ServletException(e.getMessage());
        }
    }
    private  void getSingle(HttpServletRequest req, HttpServletResponse resp)throws ServletException{
        String id=req.getParameter("id");
       ThreadEntry[] ts=ThreadTrace.getInstance().getAllThreadInfo();
        String mapstr="";
       // ThreadEntry[] ts=getinfos();
          if(!CommonUtils.isEmpty(ts))  {
        for(ThreadEntry  t:ts){
          if(t.getId()==Long.parseLong(id)){
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("status","ok");
        map.put("result",t.getStackTrace());
         mapstr=JSONUtils.toJSONString(map);

        }
        }
          }
        try{
            resp.getOutputStream().write(mapstr.getBytes(Constants.ENCODING));
            resp.setContentType("text/json; charset=UTF-8");
        }catch(Exception e){
            throw new ServletException(e.getMessage());
        }
    }
}
